<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="3">
        <el-input v-model="filterText" placeholder="关键字过滤" />
        <el-tree
          ref="treeBox"
          :data="data2"
          :props="defaultProps"
          :filter-node-method="filterNode"
          :default-expanded-keys="[10]"
          node-key="id"
          class="filter-tree custom-tree"
          highlight-current
        />
      </el-col>
      <el-col :span="21">
        <div class="filter-container">
          <el-cascader
            v-model="selectedOptions"
            :options="data2"
            placeholder="选择部门，不选默认为全部（可关键字搜索）"
            style="width: 100%; margin-bottom: 10px"
            expand-trigger="hover"
            change-on-select
            filterable
            clearable
          />
        </div>
        <div class="filter-container">
          <el-input v-model="listQuery.filterField1" style="width: 200px" placeholder="标题关键字" class="filter-item" @keyup.enter.native="handleFilter"/>
          <el-select v-model="listQuery.filterField2" placeholder="状态" clearable style="width: 110px" class="filter-item">
            <el-option
              v-for="item in [{ value: 1, text: '选项一' }, { value: 2, text: '选项二' }, { value: 3, text: '选项三' }]"
              :key="item.value"
              :label="item.text"
              :value="item.value"
            />
          </el-select>
          <el-date-picker
            v-model="listQuery.filterField3"
            :editable="false"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 360px; height: 40px; bottom: 4px;"
          />
          <el-button v-waves v-permission="permission.search" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">筛选</el-button>
          <el-checkbox v-model="showColumn" class="filter-item">显示全部列</el-checkbox>
        </div>
        <div class="filter-container">
          <el-button v-waves v-permission="permission.add" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">新增</el-button>
          <el-button v-waves class="filter-item" type="primary" icon="el-icon-delete" @click="tabDialogVisible = true">TabDialog</el-button>
          <el-button v-waves v-permission="permission.delete" class="filter-item" type="danger" icon="el-icon-delete" @click="handleDelete('batch')">删除</el-button>
          <el-button v-waves v-permission="permission.export" :loading="downloadLoading" class="filter-item" icon="el-icon-download" @click="handleDownload">导出</el-button>
          <el-button v-waves loading class="filter-item" icon="el-icon-search">Loading效果</el-button>
          <el-button v-waves class="filter-item" type="success" @click="handleConfirm1">Success Confirm</el-button>
          <el-button v-waves class="filter-item" type="warning" @click="handleConfirm2">Warning Confirm</el-button>
          <el-popover
            class="custom-popover"
            placement="top">
            <p>这是一段内容这是一段内容确定删除吗？</p>
            <div style="text-align: right; margin: 0">
              <el-button size="mini" type="text" @click="visible2 = false">取消</el-button>
              <el-button type="primary" size="mini" @click="visible2 = false">确定</el-button>
            </div>
            <el-button slot="reference" type="primary">Popover</el-button>
          </el-popover>
          <el-upload class="upload-demo" action="https://jsonplaceholder.typicode.com/posts/">
            <el-button type="primary">点击上传</el-button>
          </el-upload>
        </div>
        <el-table
          v-loading="listLoading"
          :data="list"
          element-loading-text="加载中"
          tooltip-effect="light"
          border
          fit
          stripe
          show-summary
          @selection-change="handleSelectionChange"
          @sort-change="handleSort"
        >
          <el-table-column type="selection" width="60" align="center"/>
          <el-table-column label="ID" prop="id" min-width="180" align="center" sortable="custom"/>
          <el-table-column label="标题" prop="title" min-width="500" align="center"/>
          <el-table-column label="副标题" prop="title" min-width="200" align="center" show-overflow-tooltip/>
          <el-table-column v-if="showColumn" label="作者" prop="author" min-width="110" align="center" sortable="custom"/>
          <el-table-column label="点击量" prop="pageviews" min-width="100" align="center" sortable="custom"/>
          <el-table-column class-name="status-col" label="状态" min-width="80" align="center" sortable="custom">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status | statusFilter" size="small">{{ scope.row.status }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="发布时间" prop="created_at" min-width="180" align="center" sortable="custom">
            <template slot-scope="scope">
              <i class="el-icon-time"/>
              <span>{{ scope.row.display_time }}</span>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="handleViewOrEdit(scope.row, 'view')">查看</el-button>
              <el-button type="text" size="small" @click="handleViewOrEdit(scope.row, 'update')">编辑</el-button>
              <el-button type="text" size="small" @click="handleDelete('single', scope.row)">删除</el-button>
              <!-- <el-button size="mini" @click="handleDefault('info')">查看</el-button>
              <el-button type="primary" size="mini" @click="handleDefault('success')">编辑</el-button>
              <el-button type="danger" size="mini" @click="handleDefault('error')">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination-container">
          <el-pagination
            v-show="total>0"
            :current-page="listQuery.page"
            :page-sizes="[10,20,50,100]"
            :page-size="listQuery.limit"
            :total="total"
            background
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <edit
          ref="edit"
          :dialog-form-visible="dialogFormVisible"
          :dialog-status="dialogStatus"
          :form="form"
          :is-view="isView"
          @cancel="handleCloseDialog"
          @reset="resetForm"
        />
        <el-dialog :visible="tabDialogVisible" width="70%" title="Tab样例" @close="handleCloseDialog">
          <tab-dialog />
        </el-dialog>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import edit from './edit'
import tabDialog from '../tab/index'
import { getList } from '@/api/table'
import { parseTime } from '@/utils'

export default {
  name: 'TemplateListServer',
  components: { edit, tabDialog },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    return {
      permission: {
        search: 'list_server/search',
        add: 'list_server/add',
        eidt: 'list_server/edit',
        delete: 'list_server/delete',
        export: 'list_server/export'
      },
      tabDialogVisible: false,
      visible2: false,
      selectedOptions: ['Level0', 'Level1', 'Level11', 'Level112'],
      filterText: '',
      data2: [
        {
          id: 0,
          value: 'Level0',
          label: 'XXX品牌',
          children: [
            {
              id: 1,
              value: 'Level1',
              label: '北区',
              children: [
                {
                  id: 4,
                  value: 'Level11',
                  label: '辽宁省',
                  children: [
                    {
                      id: 9,
                      value: 'Level111',
                      label: '沈阳市'
                    },
                    {
                      id: 10,
                      value: 'Level112',
                      label: '大连市'
                    }
                  ]
                }
              ]
            },
            {
              id: 2,
              value: 'Level2',
              label: '东区',
              children: [
                {
                  id: 5,
                  value: 'Level21',
                  label: '上海市'
                },
                {
                  id: 6,
                  value: 'Level22',
                  label: '浙江省'
                }
              ]
            },
            {
              id: 3,
              value: 'Level3',
              label: '南区',
              children: [
                {
                  id: 7,
                  value: 'Level31',
                  label: '广东省'
                },
                {
                  id: 8,
                  value: 'Level32',
                  label: '湖南省'
                }
              ]
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      list: null,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        filterField1: null,
        filterField2: null,
        filterField3: null,
        sortOrder: null,
        sortProp: null
      },
      total: null,
      showColumn: false,
      dialogFormVisible: false,
      form: {
        id: '',
        title: '',
        pageviews: '',
        status: '',
        display_time: null,
        select: '',
        switch: null,
        type: [],
        resource: [],
        desc: ''
      },
      dialogStatus: '',
      isView: false,
      selectionObj: [],
      downloadLoading: false
    }
  },
  watch: {
    filterText(val) {
      this.$refs.treeBox.filter(val)
    }
  },
  created() {
    this.getList()
    this.$nextTick(() => {
      this.$refs.treeBox.setCurrentKey(10)
    })
  },
  methods: {
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 获取列表数据
    getList() {
      this.listLoading = true
      getList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.data.length
        this.listLoading = false
      })
    },
    // 通过过滤条件查询
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 排序
    handleSort({ column, prop, order }) {
      this.listQuery.sortProp = prop
      this.listQuery.sortOrder = order
      this.handleFilter()
    },
    // 弹出查看或者编辑弹框
    handleViewOrEdit(row, handleType) {
      var { display_time } = row
      this.form = Object.assign({}, row)
      this.form.display_time = new Date(display_time)
      this.dialogStatus = handleType
      this.isView = handleType === 'view'
      this.dialogFormVisible = true
      this.$refs['edit'].clearValidate()
    },
    // 弹出新建弹框
    handleCreate() {
      this.resetForm()
      console.log('reset', this.form)
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 重置弹框表单
    resetForm() {
      this.form = {
        id: '',
        title: '',
        pageviews: '',
        status: '',
        display_time: null,
        select: '',
        switch: null,
        type: [],
        resource: [],
        desc: ''
      }
      this.$refs['edit'].clearValidate()
    },
    // 单条删除或者批量删除
    handleDelete(type, row) {
      if (type === 'single') {
        // 单条删除
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(() => {
            this.$message({
              type: 'success',
              message: `删除成功，删除了ID为${row.id}的数据`
            })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
      } else {
        // 批量删除
        if (this.selectionObj.length > 0) {
          this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(() => {
              var ids = this.selectionObj.map(x => {
                return x.id
              })
              this.$message({
                message: `删除成功，删除了ID为${ids.join(',')}的数据`,
                type: 'success'
              })
            })
            .catch(() => {
              this.$message({
                type: 'info',
                message: '已取消删除'
              })
            })
        } else {
          this.$message('请选择需要删除的数据')
        }
      }
    },
    // 导出Excel
    handleDownload() {
      this.$message('后端导出')
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => {
        if (j === 'insert_tms' || j === 'update_tms') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    // 换页
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    // 修改每页limit
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    // 多选或取消多选
    handleSelectionChange(selection) {
      this.selectionObj = selection
    },
    // 用于演示的按钮
    handleDefault(type) {
      switch (type) {
        case 'success':
          this.$notify({
            title: '成功',
            message: '演示按钮，没有实际功能',
            type: 'success'
          })
          break
        case 'warning':
          this.$notify({
            title: '警告',
            message: '演示按钮，没有实际功能',
            type: 'warning'
          })
          break
        case 'info':
          this.$notify.info({
            title: '警告',
            message: '演示按钮，没有实际功能'
          })
          break
        case 'error':
          this.$notify.error({
            title: '警告',
            message: '演示按钮，没有实际功能'
          })
          break
      }
    },
    // 关闭弹框
    handleCloseDialog() {
      this.dialogFormVisible = false
      this.tabDialogVisible = false
      this.resetForm()
    },
    handleConfirm1() {
      this.$confirm('成功提示?', '成功', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'success'
      }).then(() => {
        this.$message({
          type: 'success',
          message: `您选择了确定`
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '您选择了取消'
        })
      })
    },
    handleConfirm2() {
      this.$confirm('警告提示?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: `您选择了确定`
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '您选择了取消'
        })
      })
    }
  }
}
</script>
